package org.millioncall.yueyoga.admin.action;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.millioncall.openplatform.common.PaginatedList;
import org.millioncall.openplatform.util.DateTimeUtils;
import org.millioncall.openplatform.util.NumberUtils;
import org.millioncall.openplatform.util.WebAppUtils;
import org.millioncall.yueyoga.admin.export.AbstractExcelExportTemplate;
import org.millioncall.yueyoga.admin.export.RechargeExportTemplate;
import org.millioncall.yueyoga.admin.model.Group;
import org.millioncall.yueyoga.admin.model.GroupUserModel;
import org.millioncall.yueyoga.admin.model.Member;
import org.millioncall.yueyoga.admin.model.Recharge;
import org.millioncall.yueyoga.admin.model.Remaining;
import org.millioncall.yueyoga.admin.model.Status;
import org.millioncall.yueyoga.admin.model.User;
import org.millioncall.yueyoga.admin.service.MemberService;
import org.millioncall.yueyoga.admin.service.RechargeService;
import org.millioncall.yueyoga.admin.service.RemainingService;
import org.millioncall.yueyoga.admin.service.StatusService;
import org.millioncall.yueyoga.admin.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class RechargeAction extends BaseAction {
	private RechargeService rechargeService;
	private RemainingService remainingService;
	private StatusService statusService;

	public RechargeService getRechargeService() {
		return rechargeService;
	}

	public void setRechargeService(RechargeService rechargeService) {
		this.rechargeService = rechargeService;
	}

	public RemainingService getRemainingService() {
		return remainingService;
	}

	public void setRemainingService(RemainingService remainingService) {
		this.remainingService = remainingService;
	}

	private MemberService memberService;

	public MemberService getMemberService() {
		return memberService;
	}

	public void setMemberService(MemberService memberService) {
		this.memberService = memberService;
	}

	public UserService userService;

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	/** 跳转到会员充值记录页面 */
	@RequestMapping(value = "/toMemberRecharge.jhtml")
	public String toMemberRecharge(HttpServletRequest request, ModelMap model) {
		super.initFrontHeader(request, model);

		int start = 0, rechargeStart = 0;
		int limit = 6;
		int memberId = 0;
		Double yje = 0.0d;
		Integer score = 0;
		String pageNo = request.getParameter("pageNo");
		String rechargePageNo = request.getParameter("rechargePageNo");
		String pageSize = request.getParameter("pageSize");
		if (StringUtils.isNotBlank(pageSize)) {
			limit = Integer.parseInt(pageSize);
		}
		if (StringUtils.isNotBlank(pageNo)) {
			start = (Integer.parseInt(pageNo) - 1) * limit;
		}
		if (StringUtils.isNotBlank(rechargePageNo)) {
			rechargeStart = (Integer.parseInt(rechargePageNo) - 1) * limit;
		}

		String strMemberId = request.getParameter("memberId");
		if (strMemberId != null) {
			memberId = Integer.parseInt(strMemberId);
		}
		// 会员原金额
		Remaining remaining = remainingService.findyje(memberId);
		if (remaining != null) {
			yje = remaining.getRemaining();
			score = remaining.getScore();
			if (score == null) {
				score = 0;
			}
			if (yje != null) {
				model.put("score", score);
				BigDecimal bd = new BigDecimal(yje);
				// -- 向最接近数字方向舍入的舍入模式，如果与两个相邻数字的距离相等，则向相邻的偶数舍入。
				model.put("yje", bd.setScale(1, BigDecimal.ROUND_HALF_EVEN));
			} else {
				model.put("yje", 0.0);
			}
		}
		Map<String, Object> map1 = new HashMap<String, Object>();
		List<Integer> groupIds1 = new ArrayList<Integer>();
		for (Group group : this.getUser(request).getGroups()) {
			groupIds1.add(group.getId());
		}
		map1.put("groups", groupIds1);
		map1.put("id", memberId);
		map1.put("hallcode", this.getUser(request).getOrganizationId());
		Member member = this.memberService.findById(map1);
		List<Status> status = statusService.findByType(1);// 根据类型查询父类状态
		model.put("memberStatus", status);
		if (member.getSubstatus() != null && !member.getSubstatus().equals("")) {
			Status stat = statusService.findByCode(member.getSubstatus());
			model.put("statu", stat);
			status = statusService.findByParentCode(stat.getParentcode());
			model.put("subStatuses", status);
			stat = statusService.findByCode(stat.getParentcode());
			model.put("parentStatu", stat);
		}

		// 充值记录
		PaginatedList<Recharge> list = this.rechargeService.findByMemberId(
				rechargeStart, limit, memberId);
		// 提取记录
		PaginatedList<Recharge> list_tiqu = this.rechargeService
				.findTiquByMemberId(start, limit, memberId);
		List<User> userList = this.userService.findAllUsers(map1);

		model.put("rechargeList", list);
		model.put("tiquList", list_tiqu);
		model.put("member", member);
		model.put("userList", userList);
		model.put("rechargePageNo", rechargePageNo);
		model.put("pageNo", pageNo);

		return "recharge_list";
	}

	/** 跳转到搜素充值记录页面 */
	@RequestMapping(value = "/searchRecharge.jhtml")
	public String searchRecharge(HttpServletRequest request,
			HttpServletResponse response, ModelMap model) {
		super.initFrontHeader(request, model);

		int start = 0;
		int limit = 10;
		String pageNo = request.getParameter("pageNo");
		String pageSize = request.getParameter("pageSize");
		if (StringUtils.isNotBlank(pageSize)) {
			limit = Integer.parseInt(pageSize);
		}
		if (StringUtils.isNotBlank(pageNo)) {
			start = (Integer.parseInt(pageNo) - 1) * limit;
		}

		String display = request.getParameter("display");
		if ("block".equals(display)) {
			model.put(display, display);
		}
		Map<String, Object> map = new HashMap<String, Object>();
		String strMemberId = request.getParameter("memberId");
		if (StringUtils.isNotBlank(strMemberId)) {
			map.put("memberId", Integer.parseInt(strMemberId));
			model.put("memberId", strMemberId);
		}
		String userId = request.getParameter("userId");
		if (StringUtils.isNotBlank(userId)) {
			map.put("userId", userId);
			model.put("userId", userId);
		}
		String minMoney = request.getParameter("minMoney");
		if (StringUtils.isNotBlank(minMoney)) {
			map.put("minMoney", Integer.parseInt(minMoney));
			model.put("minMoney", minMoney);
		}
		String maxMoney = request.getParameter("maxMoney");
		if (StringUtils.isNotBlank(maxMoney)) {
			map.put("maxMoney", Integer.parseInt(maxMoney));
			model.put("maxMoney", maxMoney);
		}
		String minTime = request.getParameter("minTime");
		if (StringUtils.isNotBlank(minTime)) {
			map.put("minTime", minTime + " 00:00:00");
			model.put("minTime", minTime);
		}
		String maxTime = request.getParameter("maxTime");
		if (StringUtils.isNotBlank(maxTime)) {
			map.put("maxTime", maxTime + " 23:59:59");
			model.put("maxTime", maxTime);
		}
		String logType = request.getParameter("logType");
		if (StringUtils.isNotBlank(logType)) {
			map.put("logType", logType);
			model.put("logType", logType);
		}

		List<Integer> groupIds = new ArrayList<Integer>();
		for (Group group : this.getUser(request).getGroups()) {
			groupIds.add(group.getId());
		}
		map.put("groups", groupIds);
		map.put("hallcode", this.getUser(request).getOrganizationId());

		// 充值记录
		PaginatedList<Recharge> list = null;
		if ("block".equals(display)) {
			list = this.rechargeService.findRechargeByMap(start, limit, map);
		}
		User user = this.getUser(request);
		List<GroupUserModel> userList = this.userService.findUsersByGroupId("4",
				user.getOrganizationId());

		Map<String, Object> map1 = new HashMap<String, Object>();
		map1.put("key", "organizationId");
		map1.put("value", user.getOrganizationId());
		map1.put("groups", groupIds);
		map1.put("hallcode", this.getUser(request).getOrganizationId());
		List<Member> memberList = this.memberService.findMemberByProperty(map1);
		model.put("rechargeList", list);
		model.put("userList", userList);
		model.put("memberList", memberList);
		return "recharge_search";
	}

	// 导出资金日志
	@RequestMapping(value = "/exportRecharge.jhtml")
	public void exportRecharge(ModelMap model, HttpServletRequest request,
			HttpServletResponse response) {

		super.initFrontHeader(request, model);

		int start = 0;
		int limit = 10;
		String pageNo = request.getParameter("pageNo");
		String pageSize = request.getParameter("pageSize");
		if (StringUtils.isNotBlank(pageSize)) {
			limit = Integer.parseInt(pageSize);
		}
		if (StringUtils.isNotBlank(pageNo)) {
			start = (Integer.parseInt(pageNo) - 1) * limit;
		}
		Map<String, Object> map = new HashMap<String, Object>();
		String strMemberId = request.getParameter("memberId");
		if (StringUtils.isNotBlank(strMemberId)) {
			map.put("memberId", Integer.parseInt(strMemberId));
			model.put("memberId", strMemberId);
		}
		String userId = request.getParameter("userId");
		if (StringUtils.isNotBlank(userId)) {
			map.put("userId", userId);
			model.put("userId", userId);
		}
		String minMoney = request.getParameter("minMoney");
		if (StringUtils.isNotBlank(minMoney)) {
			map.put("minMoney", Integer.parseInt(minMoney));
			model.put("minMoney", minMoney);
		}
		String maxMoney = request.getParameter("maxMoney");
		if (StringUtils.isNotBlank(maxMoney)) {
			map.put("maxMoney", Integer.parseInt(maxMoney));
			model.put("maxMoney", maxMoney);
		}
		String minTime = request.getParameter("minTime");
		if (StringUtils.isNotBlank(minTime)) {
			map.put("minTime", minTime);
			model.put("minTime", minTime);
		}
		String maxTime = request.getParameter("maxTime");
		if (StringUtils.isNotBlank(maxTime)) {
			map.put("maxTime", maxTime);
			model.put("maxTime", maxTime);
		}
		String logType = request.getParameter("logType");
		if (StringUtils.isNotBlank(logType)) {
			map.put("logType", logType);
			model.put("logType", logType);
		}

		List<Integer> groupIds = new ArrayList<Integer>();
		for (Group group : this.getUser(request).getGroups()) {
			groupIds.add(group.getId());
		}
		map.put("groups", groupIds);
		map.put("hallcode", this.getUser(request).getOrganizationId());
		// 充值记录
		PaginatedList<Recharge> list = this.rechargeService.findRechargeByMap(
				start, Integer.MAX_VALUE, map);

		RechargeExportTemplate template = new RechargeExportTemplate(list);

		response.setContentType(AbstractExcelExportTemplate.EXCEL_TYPE);
		AbstractExcelExportTemplate.setFileDownloadHeader(request, response,
				"资金日志信息表.xlsx");

		try {
			template.doExport(response.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/** 会员提取 */
	@RequestMapping(value = "/tiquRecharge.jhtml")
	public void tiquRecharge(HttpServletRequest request,
			HttpServletResponse response) {
		String msg = "";
		int memberId = 0;
		// --提取金额
		Double tqje = 0.0d;
		// --剩余金额
		Double syje = 0.0d;

		String strMemberId = request.getParameter("memberId");
		String remarks_tiqu = request.getParameter("remarks_tiqu");
		// --提取方式
		String tqfs = request.getParameter("tqfs");
		String strTiqu = request.getParameter("tiqu");
		if (StringUtils.isNotBlank(strTiqu)) {
			tqje = Double.parseDouble(strTiqu);
		}
		if (StringUtils.isNotBlank(strMemberId)) {
			memberId = Integer.parseInt(strMemberId);
		}
		String time = DateTimeUtils.getInstance().format(new Date(),
				"yyyy-MM-dd HH:mm:ss");
		Map<String, Object> map1 = new HashMap<String, Object>();
		List<Integer> groupIds1 = new ArrayList<Integer>();
		for (Group group : this.getUser(request).getGroups()) {
			groupIds1.add(group.getId());
		}
		map1.put("groups", groupIds1);
		map1.put("id", memberId);
		map1.put("hallcode", this.getUser(request).getOrganizationId());
		Member member = this.memberService.findById(map1);
		// 会员原金额
		Remaining remaining = remainingService.findyje(memberId);
		if (remaining != null) {
			syje = remaining.getRemaining();
			// --剩余金额不等于null
			if (syje != null) {
				// --剩余金额与提取金额比较
				if (syje < tqje) {
					msg = "对不起，您没有提取的足够金额!";
					WebAppUtils.ajaxResponse(response, msg);
					return;
				} else {
					syje = NumberUtils.sub(syje, tqje);
				}
			} else {
				msg = "对不起，您没有提取的足够金额!";
				WebAppUtils.ajaxResponse(response, msg);
				return;
			}
		}
		User user = this.getUser(request);
		Recharge rec = new Recharge();
		Remaining rem = new Remaining();
		rec.setCreateTime(time);
		rec.setRemarks(remarks_tiqu);
		rec.setMember(member);
		rec.setRecharge(-tqje);
		rec.setMoney(tqje);
		rec.setUser(user);
		rec.setOrganizationId(member.getOrganizationId());
		rec.setLogType("提现");
		if (StringUtils.isNotBlank(tqfs)) {
			rec.setType(Integer.valueOf(tqfs));
		}
		rem.setRemaining(syje);
		rem.setMember(member);
		rem.setMemberId(memberId);
		rem.setScore(remaining.getScore());
		int i = this.rechargeService.insert(rec);// 存入提取记录
		boolean i2 = this.remainingService.updateRemainingById(rem);// 更新最新金额
		if (i > 0 && i2) {
			msg = "提取成功!";
		} else {
			msg = "提取失败!";
		}
		WebAppUtils.ajaxResponse(response, msg);
	}

	/** 会员充值 */
	@RequestMapping(value = "/addRecharge.jhtml")
	public void addRecharge(HttpServletRequest request,
			HttpServletResponse response) {
		String msg = "";
		int memberId = 0;
		int type = 1;
		double recharge = 0.00d, money = 0.00d, xje = 0.00d;
		String strMemberId = request.getParameter("memberId");
		String strRecharge = request.getParameter("recharge");
		String strMoney = request.getParameter("money");
		String strType = request.getParameter("type");
		String remarks = request.getParameter("remarks");
		if (strMemberId != null) {
			memberId = Integer.parseInt(strMemberId);
		}
		if (StringUtils.isNotBlank(strRecharge)) {
			recharge = Double.parseDouble(strRecharge);
		}
		if (StringUtils.isNotBlank(strMoney)) {
			money = Double.parseDouble(strMoney);
		}
		if (StringUtils.isNotBlank(strType)) {
			type = Integer.parseInt(strType);
		}
		String time = DateTimeUtils.getInstance().format(new Date(),
				"yyyy-MM-dd HH:mm:ss");
		Map<String, Object> map1 = new HashMap<String, Object>();
		List<Integer> groupIds1 = new ArrayList<Integer>();
		for (Group group : this.getUser(request).getGroups()) {
			groupIds1.add(group.getId());
		}
		map1.put("groups", groupIds1);
		map1.put("id", memberId);
		map1.put("hallcode", this.getUser(request).getOrganizationId());
		Member member = this.memberService.findById(map1);
		// 会员原金额
		Remaining remaining = remainingService.findyje(memberId);
		if (remaining != null) {
			Double yje = remaining.getRemaining();
			if (yje != null) {
				xje = NumberUtils.add(recharge, yje);
			} else {
				xje = recharge;
			}
		}
		User user = this.getUser(request);
		Recharge rec = new Recharge();
		Remaining rem = new Remaining();
		if (StringUtils.isNotBlank(time)) {
			rec.setCreateTime(time);
		}
		rem.setRemaining(xje);
		rem.setMember(member);
		rem.setMemberId(memberId);
		rem.setScore(remaining.getScore());
		rec.setRecharge(recharge);
		rec.setMoney(money);
		rec.setRemarks(remarks);
		rec.setMember(member);
		rec.setUser(user);
		rec.setType(type);
		rec.setLogType("充值");
		rec.setOrganizationId(member.getOrganizationId());
		int i = this.rechargeService.insert(rec);// 存入充值记录
		boolean i2 = this.remainingService.updateRemainingById(rem);// 更新最新金额
		if (i > 0 && i2) {
			if (type == 1) {
				strType = "现金";
			} else if (type == 2) {
				strType = "刷卡";
			} else if (type == 3) {
				strType = "转账";
			} else {
				strType = "支票";
			}
			msg = "{'success':true, 'item': {'recharge':'" + recharge
					+ "', 'money':'" + money + "','type':'" + strType
					+ "', 'remarks': '" + remarks + "', 'username': '"
					+ user.getUsername() + "'}}";
		} else {
			msg = "{'success': false, 'msg': '充值失败！'}";
		}

		WebAppUtils.ajaxResponse(response, msg);
	}

	public StatusService getStatusService() {
		return statusService;
	}

	public void setStatusService(StatusService statusService) {
		this.statusService = statusService;
	}
}
